<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script src="./js/ajax.min.js"></script>
  <script>
    ready(function () {
      $ajax({
        from: 'zh', to: 'en', query: '哈哈', transtype: 'translang', simple_means_flag: 3,
        sign: 693488.948161,
        token: '0d7432eba25196b0a41a86bcf8a20a98'
      }, function (res) {
        console.log(res);
      });
    });
    // $.ready的封装
    function ready(fn) {
      if (
        document.attachEvent
          ? document.readyState === 'complete'
          : document.readyState !== 'loading'
      ) {
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    }

    // 基于jq封装的ajax请求
    function $ajax(param, callback, errcallback) {
      if (param && typeof param === 'function') {
        if (callback) {
          errcallback = callback;
        }
        callback = param;
        param = undefined;
      }

      ajax({
        type: 'get',
        url: 'https://fanyi.baidu.com/v2transapi',
        timeout: 3000,
        data: param,
        success: function (res) {
          if (callback && typeof callback === 'function') {
            callback(res);
          }
        },
        error: function (err) {
          ajaxErr(err);
          if (err && typeof errcallback === 'function') {
            errcallback(err);
          }
        }
      });
    }
    //处理错误请求
    function ajaxErr(err) {
      if (err) {
        switch (err.status) {
          case 400:
            err.message = '错误请求';
            break;
          case 401:
            err.message = '未授权，请重新登录';
            break;
          case 403:
            err.message = '拒绝访问';
            break;
          case 404:
            err.message = '请求错误,未找到该资源';
            break;
          case 405:
            err.message = '请求方法未允许';
            break;
          case 408:
            err.message = '请求超时';
            break;
          case 500:
            err.message = '服务器端出错';
            break;
          case 501:
            err.message = '网络未实现';
            break;
          case 502:
            err.message = '网络错误';
            break;
          case 503:
            err.message = '服务不可用';
            break;
          case 504:
            err.message = '网络超时';
            break;
          case 505:
            err.message = 'http版本不支持该请求';
            break;
          default:
            err.message = '连接错误';
        }
      } else {
        err.message = '连接到服务器失败';
      }
      alert(err.message);
    }

  </script>
</body>

</html>